<template>
	<view style='padding-top: 10vh;'>
		<view>
			<view>
				<img src='/static/logo.png' style='width:200px;height:200px;margin:auto;display: block;' />

			</view>
			<view style='color:#909399;text-align: center;padding:10px'>新会名苑新天地停车扫码减免</view>
			<view>
				<view class="cu-form-group">
					<view class="title" @tap="plateShow = true">车牌号</view>
					<input placeholder="请点此输入" disabled="inputDisabled" @tap="plateShow = true"
						v-model.trim="plateNo" />
					<plate-input v-if="plateShow" :plate="plateNo" @export="setPlate" @close="plateShow = false" />
				</view>
			</view>
			<view v-if='freeHours < 24' style='padding:10px;color:#606266;'>本次最高可减免<text style='color:red'> {{freeHours}} </text>小时</view>
			<view v-if='plateNos && plateNos.length > 0' class='container'>
				<text v-for='item in plateNos' class='box' @click='setCarNumber(item)'>
					{{item}}
				</text>
			</view>
			<view v-if='hadPhone' style='margin-top:50px'>
				<view
					style='color:#fff;background-color: #2979ff;margin: 20px;border-radius: 20px;text-align: center;padding:10px;'
					@click='submit'>确认减免</view>
				<view style='text-align: center;color:#606266;padding-top:20px;'>{{store.name}}停车码</view>
				<view v-if='bannerImages != ""'>
					<img @click='toUrl(bannerImages.link)' :src='bannerImages.image' class="responsive-image">
				</view>
			</view>
			<view v-else>
				<view style='padding:20px'>
					<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber"
						style='border-radius: 20px;background-color: #19be6b;color:#fff'>手机号码登录</button>
				</view>
			</view>
		</view>

	</view>
</template>

<script>
	import plateInput from '@/components/uni-plate-input/uni-plate-input.vue';
	export default {
		components: {
			plateInput
		},
		data() {
			return {
				plateNo: '',
				plateShow: false,
				inputDisabled: true,
				freeHours: 0,
				show: true,
				hadPhone: false,
				plateNos: [],
				storeId: 0,
				store: '',
				time: '',
				bannerImages: ''
			};
		},
		onShow() {

		},
		onLoad(options) {
			console.log(123, options)
			if (typeof(options.scene) != 'undefined') {
				let data = options.scene.split('-')
				console.log('data', data)
				this.storeId = data[0]
				if (data.length == 2) {
					this.time = data[1]
				}

				let api_token = uni.getStorageSync('api_token')
				if (api_token == '') {
					this.wxLogin()
				} else {
					this.getStoreInfo()
				}
			} else {
				uni.showModal({
					title: '',
					content: '参数错误，请重新扫码！',
					showCancel: false,
					success: () => {}
				})
			}
		},
		methods: {
			getBanner() {
				this.request.get(`api/albums/2`).then((res) => {
					if (res.data && res.data.pictures.length > 0)
						this.bannerImages = res.data.pictures[0]
					console.log(this.bannerImages)
				})
			},
			toUrl(page) {
				if (page) {
					uni.navigateTo({
						url: page
					})
				}
			},
			setCarNumber(number) {
				this.plateNo = number
			},
			getStoreInfo() {
				this.request.get(`public/stores`, {
					'@filter': `entity.getId() == ${this.storeId}`
				}).then((res) => {
					console.log('store', res.data)
					// 门店关了或者时间超过3分钟，就会失效
					let now = new Date().getTime()
					if (res.data[0].status == 0) {
						uni.showModal({
							title: '',
							content: '门店停车码已失效,请联系管理员！',
							showCancel: false,
							success: () => {
								uni.switchTab({
									url: '/pages/index/index'
								})
							}
						})
					} else {
						this.store = res.data[0]
						// 判断门店是否设置了固定码，如果没有设置的，判断是否已经超时
						if (this.store.config == null || typeof(this.store.config.fixedCode) == 'undefined' || this.store.config.fixedCode == false) {
							// 设置了非固定码的，参数必须带时间，否则不能扫
							if(this.time == ''){
								uni.showModal({
									title: '',
									content: '停车码已经失效，请重新扫码！',
									showCancel: false,
									success: () => {
										uni.switchTab({
											url: '/pages/index/index'
										})
									}
								})
								return
							}
							let now = new Date()
							now = now.getTime()
							if ((parseInt(now) - parseInt(this.time)) > 180000) {
								uni.showModal({
									title: '',
									content: '停车码已经失效，请重新扫码！',
									showCancel: false,
									success: () => {
										uni.switchTab({
											url: '/pages/index/index'
										})
									}
								})
								return
							}
						}

						if (res.data[0].freeHours) {
							this.freeHours = res.data[0].freeHours
						} else {
							uni.showModal({
								title: '',
								content: '无可优惠时长！',
								showCancel: false,
								success: () => {
									uni.switchTab({
										url: '/pages/index/index'
									})
								}
							})
						}
					}
				})
				// 判断是否已经有客户信息，无的，依然要获取
				this.request.get(`api/user`, {
					'@expands': '["entity.profile"]'
				}).then((res) => {
					console.log('info', res.data)
					if (res.data.profile.__metadata && res.data.profile.__metadata.vehicleNos) {
						this.plateNos = res.data.profile.__metadata.vehicleNos
					}
					if (res.data.profile.__metadata.phone == null || res.data.profile.__metadata.phone == '') {
						this.hadPhone = false
					} else {
						this.hadPhone = true
					}
				})
			},
			submit() {
				if (this.plateNo == '') {
					uni.showToast({
						title: '请输入车牌号码!',
						icon: 'none'
					})
					return
				}
				let data = {
					store: this.storeId,
					vehicleNo: this.plateNo.trim(),
					parkCode: 'p220649759'
				}


				uni.showLoading()
				this.request.post(`api/parking-discounts`, data).then((res) => {
					uni.hideLoading()
					// 如果自己的车牌列表无该车牌，就记录
					if (this.plateNos.indexOf(this.plateNo.trim()) === -1) {
						this.plateNos.push(this.plateNo.trim())
						this.request.put(`api/user-profile`, {
							vehicleNos: this.plateNos
						})
					}
					uni.showModal({
						title: '',
						content: '减免成功！',
						showCancel: false,
						success: () => {
							uni.switchTab({
								url: `/pages/mine/park-info?plateNo=${this.plateNos}`
							})
						}
					})
				}).catch((err) => {
					uni.hideLoading()
				})
			},
			setPlate(plate) {
				if (plate.length >= 7) this.plateNo = plate;
				this.plateShow = false;
			},
			wxLogin() {
				let _this = this
				uni.login({
					success(result) {
						let code = result.code
						_this.request.get(`wechat/mini/login`, {
							code
						}).then((res) => {
							console.log('login', res)
							const token = res.data.token
							uni.setStorageSync('api_token', token)
							_this.getStoreInfo()
						})
					}
				})
			},
			getPhoneNumber(e) {
				let _this = this
				if (typeof(e.detail.iv) == 'undefined') {
					uni.showToast({
						title: '获取失败，请重试',
						icon: 'none'
					})
					return
				} else {
					uni.showLoading()
					uni.login({
						provider: "weixin",
						success: function(res) {
							let data = {
								code: res.code
							}
							_this.request.get("wechat/mini/login", data).then((res) => {
								uni.setStorageSync('api_token', res.data.token);
								if (res.data.data.session_key) {
									let data = {
										sessionKey: res.data.data.session_key,
										iv: e.detail.iv,
										encryptedData: e.detail.encryptedData,
									}
									_this.request.post(`wechat/decrypt-data`, data).then((res) => {
										_this.phone = res.data.phoneNumber
										console.log('phone', res);
										//更新手机号码
										_this.request.put(`api/user-profile`, {
											phone: res.data.phoneNumber
										}).then((res) => {
											_this.hadPhone = true
											uni.hideLoading()
										})
									})
								} else {
									uni.hideLoading()
									uni.showToast({
										title: '获取手机号码失败！',
										icon: 'none'
									})
								}
							})
						},
					});
				}
			}
		}
	};
</script>

<style lang="scss">
	.cu-form-group {
		border-top: 1px solid #eee;
		border-bottom: 1px solid #eee;
		background-color: #ffffff;
		padding: 1upx 30upx;
		display: -webkit-box;
		display: -webkit-flex;
		display: -ms-flexbox;
		display: flex;
		align-items: center;
		min-height: 100upx;
		justify-content: space-between;
	}

	.car-number {
		margin: 5px;
		padding: 5px 10px;
		background-color: #2979ff;
		font-size: 14px;
		color: #fff;
		border-radius: 5px;
	}

	.container {
		display: flex;
		flex-wrap: wrap;
	}

	.box {
		margin: 1%;
		/* 可以根据需要调整间距 */
		padding: 10px;
		/* 内边距 */
		border: 1px solid #606266;
		/* 边框 */
		color: #606266;
		border-radius: 3px;
		text-align: center;
		/* 以下是样式，根据需要自定义 */
		flex: 0 0 auto;
		/* 不伸缩，固定宽度，根据内容自动换行 */
		min-width: 25%;
		/* 最小宽度 */
	}
</style>